<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card>
      <!-- 警告 -->
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>

      <!-- 步骤条 -->
      <el-steps
        :space="200"
        :active="currentActive - 0"
        finish-status="success"
        :align-center="true"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- 表单 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <!-- Tabs 标签页 -->
        <el-tabs
          :tab-position="'left'"
          v-model="currentActive"
          :before-leave="beforeTagsLeave"
          @tab-click="tabClickHandler"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="">
              <!-- 级联选择器 -->
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              v-for="item in manyTableDate"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="cb"
                  v-for="(cb, i) in item.attr_vals"
                  :key="i"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTableDate"
              :key="item.attr_id"
            >
              <el-input :value="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headersObj"
              :on-success="handlerSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 预览图片 -->
    <el-dialog title="预览图片" :visible.sync="previewVisible" width="50%">
      <img :src="previewImg" alt="" class="previewImg" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  name: 'Add',
  data() {
    return {
      //   当前进度下标 标签页的name
      currentActive: '0',
      //   添加商品的表单信息
      addForm: {
        goods_name: '',
        goods_price: 1,
        goods_weight: 1,
        goods_number: 1,
        // 以为','分割的分类列表 目前是数组
        goods_cat: [1, 3, 6],
        // 上传的图片临时路径（对象）
        pics: [],
        // 商品介绍
        goods_introduce: '',
        // 商品的参数（数组），包含 `动态参数` 和 `静态属性`
        attrs: [],
      },
      //   添加商品的表单信息规则
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
        ],
      },
      //   商品类别列表
      cateList: [],
      //   类别配置选项
      cateProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
      },
      //   动态参数列表
      manyTableDate: [],
      //   静态属性列表
      onlyTableDate: [],
      //   上传路径
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      //   设置上传的请求头部
      headersObj: {
        Authorization: window.sessionStorage.getItem('token'),
      },
      //   预览图片的路径
      previewImg: '',
      //   是否开启预览窗口
      previewVisible: false,
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    //   获取商品类别列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200)
        return this.$message.error('获取类别列表失败')

      this.cateList = res.data
    },
    //   级联选择器发生改变
    handleChange() {
      console.log(this.addForm.goods_cat)
      if (this.addForm.goods_cat.length !== 3) {
        return (this.addForm.goods_cat = [])
      }
    },
    // 切换标签页之前的钩子
    beforeTagsLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请完成商品分类的选择')
        return false
      }
    },
    // tab 被选中时触发
    async tabClickHandler() {
      // 如果选中的为商品参数
      if (this.currentActive === '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'many' },
          }
        )
        if (res.meta.status !== 200) return this.$message.error('获取参数失败')

        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.trim().length === 0 ? [] : item.attr_vals.split(' ')
        })

        this.manyTableDate = res.data
      } else if (this.currentActive === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'only' },
          }
        )
        if (res.meta.status !== 200) return this.$message.error('获取属性失败')

        this.onlyTableDate = res.data
      }
    },
    // 处理预览图片的函数
    handlePreview(file) {
      this.previewImg = file.response.data.url
      this.previewVisible = true
    },
    // 处理删除图片的函数
    handleRemove(file) {
      //   获取被删除图片的临时路径
      const path = file.response.data.tmp_path
      //   根据路径获取数组中对应的下标
      const i = this.addForm.pics.findIndex((x) => x.pic === path)
      //   根据下标删除数组对应的数据
      this.addForm.pics.splice(i, 1)
    },
    // 上传成功后的函数
    handlerSuccess(response) {
      const tmp_path = { pic: response.data.tmp_path }
      this.addForm.pics.push(tmp_path)
    },
    // 添加商品
    add() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('请输入完整的表单项目！')
        }
        // 将many only参数列表转为字符串
        // 遍历manyTableDate  将数据添加到attrs
        this.manyTableDate.forEach((item) => {
          const obj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' '),
          }
          this.addForm.attrs.push(obj)
        })
        // 遍历onlyTableDate  将数据添加到attrs
        this.onlyTableDate.forEach((item) => {
          const obj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          }
          this.addForm.attrs.push(obj)
        })
        // 克隆一个form  避免冲突
        const form = _.cloneDeep(this.addForm)
        // 将数组改以为','分割的分类列表
        form.goods_cat = form.goods_cat.join(',')
        console.log(form)
        // 添加商品
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) {
          return this.$message.error('添加失败')
        }

        this.$message.success('添加成功')
        this.$router.push('/goods')
      })
    },
  },
  computed: {
    //   商品分类id
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    },
  },
}
</script>

<style lang="less" scoped>
.el-tabs {
  margin-top: 25px;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.previewImg {
  width: 100%;
}
.el-button {
  margin-top: 15px;
}
</style>